package com.yuelao.netty.code;

import com.yuelao.netty.msg.Request;
import com.yuelao.netty.msg.Response;
import com.yuelao.util.GzipUtil;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.io.File;
import java.io.FileOutputStream;

/**
 * Description
 *
 * @author fengliye
 * @version v1.0
 * @date 14/12/2018 15:12
 * @modify detail
 * 版本       修改人        修改时间      修改内容描述
 * ---------------------------------------------
 * <p>
 * ---------------------------------------------
 */
public class CodeServerHandler extends ChannelHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        Request req = (Request) msg;
        System.out.println("Server : " + req.getId() + ", " + req.getName() + ", " + req.getRequestMessage());
        try {
            byte[] attachment = GzipUtil.ungzip(req.getAttachment());
            String path = System.getProperty("user.dir") + File.separatorChar + "feng002.png";
            FileOutputStream fos = new FileOutputStream(path);
            fos.write(attachment);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Response resp = new Response();
        resp.setId(req.getId());
        resp.setName("resp" + req.getId());
        resp.setResponseMessage("1111111111111111111111111111111############" + req.getId());
        ctx.writeAndFlush(resp);//.addListener(ChannelFutureListener.CLOSE);
        ctx.flush();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
